<template>
    <div class="common-layout">
      <el-container>
        <el-header class="header-container">
          <div class="logo">
            <img src="../img/yz.webp" alt="永泽游戏网" />
            <span class="yz">永泽游戏网 - 管理员后台</span>
          </div>
          <div class="header-right">
            <el-button type="danger" @click="logout">退出登录</el-button>
          </div>
        </el-header>
        <el-container>
          <el-aside width="200px">
            <el-scrollbar>
              <el-menu>
                <el-sub-menu index="1">
                  <template #title>
                    <el-icon><setting /></el-icon>
                    <span>管理员功能</span>
                  </template>
                  <el-menu-item-group>
                    <el-menu-item index="1-1">
                      <router-link to="/checkGames">游戏管理</router-link>
                    </el-menu-item>
                    <el-menu-item index="1-2">
                      <router-link to="/home">通知公告管理</router-link>
                    </el-menu-item>
                    <el-menu-item index="1-3">
                      <router-link to="/user">用户管理</router-link>
                    </el-menu-item>
                    <el-menu-item index="1-4">
                      <router-link to="/category">游戏分类管理</router-link>
                    </el-menu-item>
                    <el-menu-item index="1-4">
                      <router-link to="/changeComments">评论管理</router-link>
                    </el-menu-item>
                  </el-menu-item-group>
                </el-sub-menu>
              </el-menu>
            </el-scrollbar>
          </el-aside>
          <el-main>
            <!-- 查询表单 -->
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
              <el-form-item label="用户名">
                <el-input v-model="formInline.username" placeholder="用户名" v-on:keyup.enter.native="onSubmit" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </el-form-item>
            </el-form>
  
            <!-- 管理员数据表格 -->
            <el-table :data="adminList" border>
              <el-table-column prop="name" label="姓名" width="150" />
              <el-table-column prop="username" label="用户名" width="200" />
              <el-table-column prop="phone" label="手机号" width="200" />
              <el-table-column prop="sex" label="性别" width="100" />
              <el-table-column prop="role" label="角色" width="150" />
              <el-table-column prop="status" label="状态" width="150">
                <template #default=" {row} ">
                  <el-tag :type="row.status === 1 ? 'success' : 'danger'" disable-transitions>
                    {{ row.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="200" />
              <el-table-column prop="updateTime" label="更新时间" width="200" />
              <el-table-column label="操作" width="500">
                <template #default="{ row }">
                  <el-button type="success" @click="onMod(row)">编辑</el-button>
                  <el-button type="danger" @click="onDelete(row)">删除</el-button>
                  <el-button
                    :type="row.status === 1 ? 'warning' : 'success'"
                    @click="toggleStatus(row)"
                  >
                    {{ row.status === 1 ? '禁用' : '启用' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
  
            <!-- 分页 -->
            <el-pagination @current-change="handleCurrentChange"
              :current-page="pageNum" :page-sizes="pageSize"
              layout="prev, pager, next" :total="totalCount">
            </el-pagination>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import request from '../axios/request'; // 确保你引入了axios请求
  import { ElMessage } from 'element-plus'; // 引入Element Plus消息提示
  import { useRouter } from 'vue-router';
  import { computed } from 'vue';
  import { useAuthStore } from '../stores/userStore';

const store = useAuthStore();
    const router = useRouter();
    const pageKey = computed(() => {
  const storedPageKey = sessionStorage.getItem('pageKey');
  return storedPageKey || `${router.path || '/game'}-${Math.random().toString(36).substr(2, 9)}`;
});
    const token = localStorage.getItem('token');
  // 页码和每页条数
  const pageNum = ref(1);
  const pageSize = ref(10);
  const totalCount = ref(0);
  
  // 表格数据
  const adminList = ref([]);
  
  // 查询表单
  const formInline = ref({
    username: '',
  });
  
  // 获取管理员列表数据
  const getAdminList = () => {
    request({
      url: '/admin/listPage', // 假设后端接口地址为 /admin/list
      method: 'post',
      data: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        param: {
                "username": formInline.value.username
            }, // 可根据用户名查询
      },
      pageKey: pageKey.value,
    })
      .then((res) => {
        if (res.data.code === 200) {
          adminList.value = res.data.data; // 将后端返回的管理员数据赋给表格
          totalCount.value = res.data.total; // 总记录数
        } else {
          ElMessage.error('获取管理员数据失败');
        }
      })
      .catch((err) => {
        console.error(err);
        ElMessage.error('请求失败，请检查网络');
      });
  };
  const logout = () => {
  // 清除本地存储中的 token 或用户信息
  request({
    url: '/login/logout',
    method: 'get',
    pageKey: pageKey.value,
  })
    .then((res) => {
      if (res.data.code === 200) {
              // 提示用户退出成功
        ElMessage({
          message: '退出登录成功',
          type: 'success',
        });
        store.logout(pageKey.value);
        // 跳转到登录页面
        router.push('/');
      } else {
        ElMessage.error('退出登录失败');
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage.error('请求失败，请检查网络');
    });

};

  // 查询操作
  const onSubmit = () => {
    getAdminList();
  };
  
  // 编辑操作
  const onMod = (row) => {
    console.log('编辑', row);
    // 打开编辑对话框并填充数据
  };
  
  // 删除操作
  const onDelete = (row) => {
    console.log('删除', row);
    // 进行删除操作
  };
  
  // 启用/禁用
  const toggleStatus = (row) => {
    console.log('切换状态', row);
    // 进行启用/禁用操作
    request({
    url: '/admin/status',
    method: 'post',
    data: {
      "id": row.id,
      "status": row.status, // 更新后的状态
    },
    pageKey: pageKey.value,
  })
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage({
          message: '状态更改成功',
          type: 'success',
          plain: true,
        });
        getAdminList(); // 重新加载表格数据
        
      } else {
        ElMessage({
          message: '状态更改失败',
          type: 'error',
          plain: true,
        });
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage({
        message: '请求失败，请检查网络连接',
        type: 'error',
        plain: true,
      });
    });
  };
  
  // 分页操作
  const handleCurrentChange = (val) => {
    pageNum.value = val;
    getAdminList(); // 刷新数据
  };
  
  onMounted(() => {
    getAdminList(); // 页面加载时获取管理员数据
  });
  </script>

<style scoped>
.common-layout {
  background: #f4f6f9; /* 浅灰蓝色背景 */
  min-height: 100vh;
  padding-bottom: 50px;
}

.el-container {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #2c3e50; /* 深蓝色头部 */
  color: #fff;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
}

.header-container .logo {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-container .logo img {
  height: 50px;
}

.header-container .yz {
  font-size: 1.5rem;
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 侧边栏样式 */
.el-aside {
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
}

.el-menu {
  border: none;
}

.el-menu-item a {
  text-decoration: none;
  color: #303133;
}

.el-menu-item.is-active {
  background-color: #3498db;
  color: #fff;
}

/* 主内容区域 */
.el-main {
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
  margin: 20px;
}

/* 表单样式 */
.demo-form-inline {
  margin-bottom: 20px;
}

.el-form-item {
  margin-right: 15px;
}

.el-input {
  width: 200px;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #3498db; /* 蓝色表头 */
  color: #fff;
  font-weight: bold;
}

.el-table td {
  vertical-align: middle;
}

/* 按钮样式 */
.el-button[type="primary"] {
  background-color: #3498db;
  border: none;
}

.el-button[type="primary"]:hover {
  background-color: #2980b9;
}

.el-button[type="success"] {
  background-color: #2ecc71;
  border: none;
}

.el-button[type="success"]:hover {
  background-color: #27ae60;
}

.el-button[type="danger"] {
  background-color: #e74c3c;
  border: none;
}

.el-button[type="danger"]:hover {
  background-color: #c0392b;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 10px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
}

.dialog-footer {
  text-align: center;
  padding: 15px;
}

/* 标签样式 */
.el-tag[type="success"] {
  background-color: #2ecc71;
}

.el-tag[type="danger"] {
  background-color: #e74c3c;
}
</style>

